package config

import (
	"encoding/json"
	"fmt"
	examples "github.com/go-git/go-git/v5/_examples"
	"io/ioutil"
	"os"
)

type Config struct {
	Gitlab struct {
		DownLocalPath   string `json:"down_local_path"`
		OriginRemoteUrl string `json:"origin_remote_url"`
		TargetRemoteUrl string `json:"target_remote_url"`
		GroupsApi       string `json:"get_groups_api"`
		ProjectsApi     string `json:"get_projects_api"`
		UsersApi        string `json:"get_users_api"` //usersapi
		SkipProject     string `json:"skip_projects"` //排除项目（不拉取指定的项目）
		AutoSkipSize    string `json:"auto_skip_size_mb"`
		RemoveLocal     bool   `json:"success_push_remove_local"` //推送成功后是否需要删除本地项目
		ProjectPrepage  string `json:"project_default_pull_pre_page"`
	}
	OriginGitlab struct {
		Username     string `json:"username"`
		Password     string `json:"password"`
		PrivateToken string `json:"private_token"`
	}
	TargetGitlab struct {
		Username     string `json:"username"`
		Password     string `json:"password"`
		PrivateToken string `json:"private_token"`
		ParentGroup  string `json:"parent_group"`
	}
	Log struct {
		LogFilePath string `json:"log_file_path"`
		RequestLog  bool   `json:"open_request_log"`
	}
}

var configObj *Config

// 获取配置
func GetConfig() *Config {
	return configObj
}

func init() {
	if configObj == nil {
		configObj = readConfig()
		if configObj.Gitlab.GroupsApi == "" {
			configObj.Gitlab.GroupsApi = "/api/v4/groups"
		}
		if configObj.Gitlab.ProjectsApi == "" {
			configObj.Gitlab.ProjectsApi = "/api/v4/projects"
		}
		if configObj.Gitlab.UsersApi == "" {
			configObj.Gitlab.UsersApi = "/api/v4/users"
		}
		if configObj.Gitlab.ProjectPrepage == "" {
			configObj.Gitlab.ProjectPrepage = "100"
		}
	}
}

/*
*
读取config.json配置文件
*/
func readConfig() *Config {
	file, err := os.Open("config.json")
	examples.CheckIfError(err)
	defer file.Close()
	data, err := ioutil.ReadAll(file)
	examples.CheckIfError(err)
	var result Config
	err = json.Unmarshal(data, &result)
	examples.CheckIfError(err)
	bytes, err := json.Marshal(result)
	fmt.Printf("配置信息：%s\n", string(bytes))
	return &result
}
